<script setup>
import ElCardBg from '@/components/ElCardBg.vue';
import { ElMessage, ElNotification } from 'element-plus';
import { MdEditor } from 'md-editor-v3'
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { getCategoryAndLabelList, releaseArticel, getArticleApi, updateArticle, uploadImage } from '@/api/article'
import { useUserStore } from '@/stores/user'
// 实例化仓库
const userStore = useUserStore()
// 实例化路由
const router = useRouter()
const route = useRoute()

// 路由id
const articleId = ref(null)
// 文章标题
const title = ref('')
// 获取到路由参数
onMounted(() => {
  articleId.value = route.params.id
  title.value = articleId.value === '0' ? '发布文章' : '修改文章'
})
// 页面进入根据路由查询当前数据
const getCurrentArticle = async () => {
  // 查询当前数据
  const res = await getArticleApi(articleId.value)
  formData.value = res.data
  mdData.value = res.data.content
  formData.value.content = ''
}
onMounted(() => {
  if (articleId.value != 0) {
    getCurrentArticle()
  }
})

// 表单数据 
const formData = ref({
  title: '',
  describe: '',
  categoryName: '',
  labelName: '',
  cover: '',
  status: 1,
  sort: 1,
  content: ''
})

// 分类数据
const categoryList = ref([])
// 标签数据
const labelList = ref([])
// 添加信息弹层
const isDialog = ref(false)
// 打开弹层
const onBasic = async () => {
  isDialog.value = true
  const { data } = await getCategoryAndLabelList()
  console.log(data);
  categoryList.value = data.category
  labelList.value = data.label
}
// 关闭弹层
const onClose = () => {
  isDialog.value = false
  formData.value = {}
}

// 上传图片的token
const headers = ref({ 'Authorization': userStore.userInfo.token })
// 上传成功的回调
const handleSuccessCover = (response) => {
  formData.value.cover = response.data
}
// 确认基本信息
const basicOk = () => {
  // 保存基本信息
  // 处理数字
  formData.value.sort = parseInt(formData.value.sort)
  // 表单校验
  // 标题：非空检查
  if (!formData.value.title.trim()) {
    ElMessage.error('标题不能为空')
    return
  }
  // 描述：非空检查，可选地可以增加长度限制
  if (!formData.value.describe.trim()) {
    ElMessage.error('描述不能为空')
    return
  }
  // 分类名称：非空检查
  if (!formData.value.categoryName.trim()) {
    ElMessage.error('分类名称不能为空')
    return
  }
  // 标签名称：非空检查
  if (!formData.value.labelName.trim()) {
    ElMessage.error('标签名称不能为空')
    return
  }
  // 封面图片：可以检查文件类型和大小，这里只做存在性检查
  if (!formData.value.cover) {
    ElMessage.error('请上传封面图片')
    return
  }
  isDialog.value = false
  ElMessage.success('保存基本信息成功!')
}

// md内容
const mdData = ref('')
// 保存md的内容
const saveContent = () => {
  formData.value.content = mdData.value
  ElMessage.success("保存文章内容成功!")
  isFlag.value = false
}

// 发布说说
const onSave = async () => {
  // 判断是否保存了内容 todo
  if (!formData.value.content && mdData.value || isFlag.value === true) {
    ElMessage.warning("文章内容忘记保存了!")
    return
  }
  if (articleId.value !== '0') {
    // 修改文章
    await updateArticle(articleId.value, formData.value)
    ElMessage.success("修改成功!")
  } else {
    // 发布接口
    await releaseArticel(formData.value)
    // 发布成功
    ElNotification({
      title: '发布成功',
      message: ({ style: 'color: #249bdb' }, "可以去网站上查看详细信息"),
    })
  }
  // 跳转路由
  router.push("/article/pigeonhole")
}
const isFlag = ref(false)
// md的图片上传接口
const onUploadImg = async (file) => {
  console.log(file);
  // 创建文件对象
  const formData = new FormData()
  // 添加文件到对象中
  formData.append('file', file[0]);
  const res = await uploadImage(formData)
  mdData.value += `![](${res.data})`
  isFlag.value = true
}
// 图片上传
</script>

<template>
  <ElCardBg :title="title">
    <template v-slot:content>
      <!-- 操作按钮 -->
      <div class="btn-box">
        <div class="save">
          <!-- 文章基本信息 -->
          <el-button type="danger" @click="onBasic" plain>请先点击填写文章基本信息</el-button>
        </div>
        <div class="op">
          <!-- 操作 -->
          <el-button type="primary" @click="onSave" v-permissionDirective>保存</el-button>
          <el-button type="" @click="router.push('/article/pigeonhole')">取消</el-button>
        </div>
      </div>
      <!-- md文本编辑器 -->
      <MdEditor style="height: 530px;" v-model="mdData" @on-save="saveContent" @on-upload-img="onUploadImg"></MdEditor>
      <!-- 填写基本信息的弹层 -->
      <el-dialog top="10vh" title="文章信息" width="600px" v-model="isDialog">
        <!-- 内容区域 -->
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="文章标题" prop="title" style="width: 400px;">
            <el-input placeholder="请输入文章标题" :maxLength="20" v-model="formData.title"></el-input>
          </el-form-item>
          <el-form-item label="文章描述" prop="describe" style="width: 400px;">
            <el-input placeholder="请输入文章描述" type="textarea" :rows="2" v-model="formData.describe"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="categoryName">
            <el-select v-model="formData.categoryName" placeholder="文章分类" clearable>
              <el-option v-for="item in categoryList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章标签" prop="labelName">
            <el-select v-model="formData.labelName" placeholder="文章标签" clearable>
              <el-option v-for="item in labelList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover">
            <el-upload :headers="headers"
              style=" height: 160px;width: 220px;border-radius: 4px;border: 1px solid #409eff;"
              :on-success="handleSuccessCover" action="/prod-api/admin/article/fileUpload" :show-file-list="false">
              <!-- 这里需要做一个判断如果存在则显示图片不存在显示按钮 -->
              <img v-if="formData.cover" :src="formData.cover" class="avatar" />
              <el-button v-else
                style="background-color: #ffffff;border: none;margin:70px 0px 0px 83px;font-size: 26px;width: 15px;height: 15px;"><span
                  style="color: #8597b4;">+</span></el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="状态" prop="" style="width: 580px;">
            <el-radio-group v-model="formData.status">
              <el-radio :value="1">公开</el-radio>
              <el-radio :value="2">隐藏</el-radio>
              <el-radio :value="3">草稿</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序" prop="" style="width: 180px;">
            <el-input type="number" v-model="formData.sort" min="1"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="small" @click="onClose">取 消</el-button>
            <el-button size="small" type="primary" @click="basicOk">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </ElCardBg>
</template>
<style lang="scss" scoped>
.btn-box {
  display: flex;
  margin-bottom: 15px;

  .op {
    margin-left: 930px;
  }
}

.el-form-item {
  width: 280px;
}

.avatar {
  width: 220px;
  height: 160px;
  object-fit: cover;
}
</style>
